package cn.historia.domain.strategy.service.rule.chain.factory;

import cn.historia.domain.strategy.model.entity.StrategyEntity;
import cn.historia.domain.strategy.repository.IStrategyRepository;
import cn.historia.domain.strategy.service.rule.chain.ILogicChain;
import lombok.*;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @package: cn.historia.domain.strategy.service.rule.chain.factory
 * @className: DefaultChainFactory
 * @author: 云溪
 * @description: 工厂
 * @date: 2025/7/24 11:18
 * @version: 1.0
 */
@Service
public class DefaultChainFactory {

    private final Map<String, ILogicChain> logicChainGroup;

    protected IStrategyRepository repository;

    /**
     * Spring会自动收集所有实现了ILogicChain接口的Bean（如DefaultLogicChain、BlackListLoginChain等），
     * 并将它们以Map的形式注入到logicChainGroup中，key是Bean的名称（如"default"、"rule_blacklist"、"rule_weight"）
     * @param logicChainGroup
     * @param repository
     */
    public DefaultChainFactory(Map<String, ILogicChain> logicChainGroup, IStrategyRepository repository){
        this.logicChainGroup = logicChainGroup;
        this.repository = repository;
    }

    public ILogicChain openLogicChain(Long strategyId){
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String[] ruleModels = strategyEntity.ruleModels();

        if(null == ruleModels || 0 == ruleModels.length) return logicChainGroup.get("default");

        ILogicChain logicChain = logicChainGroup.get(ruleModels[0]);
        ILogicChain current = logicChain;
        for(int i =1;i< ruleModels.length;i++){
            ILogicChain nextChain = logicChainGroup.get(ruleModels[i]);
            current = current.appendNext(nextChain);
        }

        current.appendNext(logicChainGroup.get("default"));

        return logicChain;

    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO {
        /** 抽奖奖品ID - 内部流转使用 */
        private Integer awardId;
        /**  */
        private String logicModel;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        RULE_WEIGHT("rule_weight", "权重规则"),
        ;

        private final String code;
        private final String info;

    }


}
